/**
 * 生成随机字符串
 * @param {*} len
 */
export const generateMixed = (len) => {
  let str = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
  var res = "";
  for(var i = 0; i < len ; i ++) {
    var id = Math.ceil(Math.random()*35);
    res += str[id];
  }
  return res;
}

/**
 * 处理富文本中的字符
 * 用于数学公式显示
 */
export const farmatMath = (towxmlFunc, str) => {
    var regex = /[+\-*/=^()[\]{}]/;
    str = str.replace(/<img(.*?)src="(.*?)"(.*?)>/g, '<image$1src="$2"$3></image>');
    if (regex.test(str) && str.indexOf('$') != -1) {
        // 处理数学公式的
        str = str.replaceAll('<p>', '')
        str = str.replaceAll('</p>', '')
        str = str.replaceAll('&lt;', '<')
        str = str.replaceAll('&gt;', '>')
        
        var escapedString = str.replace(/["\n]/g, function(match) {
          return {
            '"': "'",
            '\\': '\\\\',
          }[match];
        });
        str = towxmlFunc(escapedString,'markdown');
    } else {
        str = towxmlFunc(str,'html');
    }
    return str
}
/**
     * @desc 函数防抖
     * @param func 函数
     * @param wait 延迟执行毫秒数
     * @param immediate true 表立即执行，false 表非立即执行
     */
export const Debounce = (func, wait, immediate) => {
    let timeout
    wait = wait || 500
    immediate = immediate || true

    return function() {
        const context = this
        const args = arguments

        if (timeout) clearTimeout(timeout)
        if (immediate) {
        var callNow = !timeout
        timeout = setTimeout(() => {
            timeout = null
        }, wait)
        if (callNow) func.apply(context, args)
        } else {
        timeout = setTimeout(function() {
            func.apply(context, args)
        }, wait)
        }
    }
}

/**
   * 函数节流
   * @param fn
   * @param interval
   * @returns {Function}
   * @constructor
   */
export const Throttle = (fn, t) => {
    let last
    let timer
    const interval = t || 500
    return function() {
    const args = arguments
    const now = +new Date()
    if (last && now - last < interval) {
        clearTimeout(timer)
        timer = setTimeout(() => {
        last = now
        // console.log("实际执行函数（" + interval + "）：" + typeof fn)
        fn.apply(this, args)
        }, interval)
    } else {
        last = now
        // console.log("实际执行函数（" + interval + "）：" + typeof fn)
        fn.apply(this, args)
    }
    }
}

export function deepCopy(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }

    if (obj instanceof Date) {
        return new Date(obj.getTime());
    }

    if (obj instanceof Array) {
        return obj.reduce((arr, item, i) => {
        arr[i] = deepCopy(item);
        return arr;
        }, []);
    }

    if (obj instanceof Object) {
        return Object.keys(obj).reduce((newObj, key) => {
        newObj[key] = deepCopy(obj[key]);
        return newObj;
        }, {});
    }
}

// 图片前缀
export function imgPreFix(){
    let url = ''
    if(process.env.NODE_ENV == 'development'){
        url = "https://jxfwpt-t.oss-cn-beijing.aliyuncs.com/practice/ielts/static/img"
    } else {
        url = "https://jxfwpt-p.oss-cn-beijing.aliyuncs.com/practice/ielts/static/img"
    }
    return url
}

// 对象转路由参数
export function objectToRouteParams(obj) {
    return Object.keys(obj)
    .map(key => `${key}=${obj[key]}`)
    .join('&')
}